package com.example.localalbum.ui

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.provider.MediaStore
import android.support.media.ExifInterface
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v4.content.FileProvider
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.centling.smartSealForPhone.BuildConfig
import com.centling.smartSealForPhone.R
import com.centling.smartSealForPhone.activity.TitleBarActivity
import com.centling.smartSealForPhone.utils.ImageUtil
import com.centling.smartSealForPhone.utils.ShowToast
import com.example.localalbum.common.ImageUtils
import com.example.localalbum.common.LocalImageHelper
import kotlinx.android.synthetic.main.activity_local_album.*
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.Job
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.launch
import java.io.File
import java.io.IOException
import java.util.*

class LocalAlbum : TitleBarActivity() {

    private val allFolders = HashMap<String, List<LocalImageHelper.LocalFile>>()
    private var readingJob: Job? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_local_album)

        setTitleBarText("选择相册")
        setTitleBarLeft(R.drawable.ic_action_back)
        setTitleBarLeftClick { finish() }
        setTitleBarRight("拍照")
        setTitleBarRightClick { tryToCapturePic() }

        if (intent.getBooleanExtra("onlyCamera", false)) {
            tryToCapturePic()
            return
        }

        allFolders.clear()

        local_album_list.layoutManager = LinearLayoutManager(mContext)
        val folderAdapter = FolderAdapter(mContext, allFolders)
        local_album_list.adapter = folderAdapter

        // refresh pics
        readingJob = launch(UI) {
            pb_local_album_indicator.visibility = View.VISIBLE
            val foldersInfo = async(CommonPool) {
                LocalImageHelper.getInstance().initImage()
                return@async LocalImageHelper.getInstance().folderMap
            }
            allFolders.clear()
            allFolders.putAll(foldersInfo.await())
            folderAdapter.updateFolderName()
            pb_local_album_indicator.visibility = View.GONE
        }
    }

    private fun tryToCapturePic() {
        /*
          统计审核照片数量，判断是否继续添加照片
         */
        if (LocalImageHelper.getInstance().currentSize + LocalImageHelper.getInstance()
                        .checkedItems.size >= LocalImageHelper.getInstance()
                        .totalSize) {
            ShowToast.shortTime(
                    "最多选择" + LocalImageHelper.getInstance().totalSize + "张图片")
            return
        }

        if (ContextCompat.checkSelfPermission(mContext,
                        Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA),
                    ASK_FOR_CAMERA)
            return
        }

        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        val cameraPath = LocalImageHelper.getInstance().setCameraImgPath()
        val file = File(cameraPath)
        val uri: Uri
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".FileProvider", file)
        } else {
            uri = Uri.fromFile(file)
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
        startActivityForResult(intent, ImageUtils.REQUEST_CODE_GET_IMAGE_BY_CAMERA)
    }

    override fun onDestroy() {
        super.onDestroy()
        readingJob?.cancel()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK && requestCode == ImageUtils.REQUEST_CODE_GET_IMAGE_BY_CAMERA) {
            val cameraPath = LocalImageHelper.getInstance().cameraImgPath
            if (TextUtils.isEmpty(cameraPath)) {
                ShowToast.shortTime("图片获取失败")
                return
            }
            val file = File(cameraPath)
            if (file.exists()) {
                // update external capture photo
                ImageUtils.scanPhoto(file)
                val uri = Uri.fromFile(file)
                val localFile = LocalImageHelper.LocalFile()
                localFile.path = cameraPath
                localFile.thumbnailUri = uri.toString()
                localFile.originalUri = uri.toString()
                localFile.orientation = getBitmapDegree(cameraPath)
                LocalImageHelper.getInstance().checkedItems.add(localFile)
                LocalImageHelper.getInstance().isResultOk = true
                Handler().postDelayed({ finish() }, 1000)
            } else {
                ShowToast.shortTime("图片获取失败")
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
                                            grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (ASK_FOR_CAMERA == requestCode && Manifest.permission.CAMERA == permissions[0]) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                tryToCapturePic()
            } else {
                ShowToast.shortTime("该功能需要相机权限支持")
            }
        }
    }

    private fun getBitmapDegree(path: String): Int {
        var degree = 0
        try {
            val exifInterface = ExifInterface(path)
            val orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL)
            when (orientation) {
                ExifInterface.ORIENTATION_ROTATE_90 -> degree = 90
                ExifInterface.ORIENTATION_ROTATE_180 -> degree = 180
                ExifInterface.ORIENTATION_ROTATE_270 -> degree = 270
                else -> {
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return degree
    }

    private inner class FolderAdapter internal constructor(internal var context: Context, internal var folders: Map<String, List<LocalImageHelper.LocalFile>>) : RecyclerView.Adapter<ViewHolder>() {
        internal var folderNames: MutableList<String> = ArrayList()

        init {
            updateFolderName()
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            return ViewHolder(LayoutInflater.from(context)
                    .inflate(R.layout.ll_local_album_foler_item, parent, false))
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val name = folderNames[position]
            val files = folders[name]
            holder.textView.text = String.format(Locale.CHINA, "%s(%d)", name, files?.size ?: 0)
            if (files == null) {
                return
            }
            if (files.isNotEmpty()) {
                holder.imageView.visibility = View.VISIBLE
                ImageUtil.loadImage(files.get(0).thumbnailUri, holder.imageView)
            } else {
                holder.imageView.visibility = View.GONE
            }
            holder.itemView.setOnClickListener {
                val intent = Intent(mContext, LocalAlbumDetail::class.java)
                intent.putExtra("local_folder_name",
                        folderNames[holder.adapterPosition])
                intent.flags = Intent.FLAG_ACTIVITY_FORWARD_RESULT
                startActivity(intent)
                finish()
            }
        }

        override fun getItemCount(): Int {
            return folders.size
        }

        internal fun updateFolderName() {
            folderNames.clear()
            for ((key) in folders) {
                folderNames.add(key)
            }

            folderNames.sortWith(Comparator { arg0, arg1 ->
                val num1 = LocalImageHelper.getInstance().getFolder(arg0).size
                val num2 = LocalImageHelper.getInstance().getFolder(arg1).size
                num2.compareTo(num1)
            })
            notifyDataSetChanged()
        }
    }

    private inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        internal var imageView: ImageView = itemView.findViewById(R.id.iv_local_album_folder_preview)
        internal var textView: TextView = itemView.findViewById(R.id.iv_local_album_folder_name)
    }

    companion object {
        private const val ASK_FOR_CAMERA = 1000
    }
}
